//获取加密字符串
import { getPermissionToken } from '@/api/qss/index.js'
import { smEncrypto } from '@/utils/jsencrypt'

export function getEncryptedStr() {
    // 批量获取存储数据
    const projectsList = uni.getStorageSync('projects');
    const activeProject = uni.getStorageSync('activeProject');
    const userInfo = uni.getStorageSync('userInfo');

    // 数据验证
    if (!userInfo?.idCard || !userInfo?.name || !userInfo?.phonenumber) {
        return Promise.reject(new Error('用户信息不完整'));
    }

   let processedProjects = []
    if (activeProject?.id) {
        // return Promise.reject(new Error('未找到项目'));
      processedProjects = markActiveProject(projectsList, activeProject.id);
    }

    // 优化项目标记逻辑

    // 构建参数对象
    const params = {
        idNo: userInfo.idCard,
        userName: userInfo.name,
        phone: userInfo.phonenumber,
        projects: processedProjects
    };
    console.log(params,'params')

    // console.log('请求参数:', JSON.stringify(params));

    // 加密数据
    const encryptedStr = smEncrypto(JSON.stringify(params));
    // console.log('加密后数据:', encryptedStr);

    // 返回 Promise 链
    return getPermissionToken({ data: encryptedStr })
        .then(res => {
            if (res.code === 200 && res.data?.token) {
                uni.setStorageSync('authCode', res.data.token);
                return { success: true, token: res.data.token };
            } else {
                return Promise.reject(new Error(`获取令牌失败: ${res.message || '未知错误'}`));
            }
        })
        .catch(error => {
            console.error('getEncryptedStr 执行失败:', error);
            return Promise.reject(error);
        });
}

// 辅助函数：标记活跃项目
function markActiveProject(projectsList, activeProjectId) {
    if (!Array.isArray(projectsList) || !activeProjectId) {
        return projectsList || [];
    }

    return projectsList.map(project => ({
        ...project,
        flagProject: project.id === activeProjectId
    }));
}

//身份证号码中间隐藏显示信号
export function showIdCard(idCard) {
    // console.log(idCard,'idCard')
	return idCard.replace(/(\d{4})\d{10}(\d{4})/, '$1********$2');
}


